package com.toman.ui.work.device;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Adpter.ItemTypeCheckOldAdapter;
import com.toman.Enum.NetworkEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.R;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.JsonUtils;
import com.toman.Util.ViewUtil;
import com.toman.widget.MyListView;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.bean.ItemListBean;
import com.toman.bean.ItemTypeBean;
import com.toman.toolbar.ToolBarActivity;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class CompleteEquipmentAddActivity extends ToolBarActivity implements ItemTypeCheckOldAdapter.ActionClickListener {

    ItemListAdapter adapter;
    List<ItemListBean> list = new ArrayList<ItemListBean>();
    String deviceID = "";
    @BindView(R.id.tv_device)
    TextView tvDevice;
    @BindView(R.id.rl_device)
    RelativeLayout rlDevice;

    @BindView(R.id.tv_remark_name)
    TextView tvRemarkName;
    @BindView(R.id.et_remark)
    EditText etRemark;

    @BindView(R.id.lv_result)
    MyListView lvResult;
    @BindView(R.id.ll)
    LinearLayout ll;
    List<ItemTypeBean> list1 = new ArrayList<ItemTypeBean>();
    ItemTypeCheckOldAdapter adapter1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complete_equipment_add);
        ButterKnife.bind(this);
        initView();
        initToolBar("新增完好检查");
        initIntent();
    }
    private void initIntent() {
        if (!StringUtils.isEmpty(getIntent().getStringExtra("device_id"))){
            deviceID=getIntent().getStringExtra("device_id");
            tvDevice.setText(getIntent().getStringExtra("device_name"));
            getDevice();
        }
    }
    private void initView() {
        adapter=new ItemListAdapter(this);
        adapter1 = new ItemTypeCheckOldAdapter(this);
        lvResult.setAdapter(adapter1);
        adapter1.setActionClickListener(this);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }


    public void deviceDialog() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        ListView lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);

        builder                //对话框的标题
                .setTitle("选择设备")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //获取用户输入的“用户名”，“密码”


                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();
        device();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapter.getItem(i);
                deviceID = bean.getID();
                tvDevice.setText(bean.getName());
                getDevice();
                dialog.dismiss();
            }
        });

    }


    public void device() {


        OkHttpUtils
                .get(NewBaseUrl.device_list_get)
                .params("departmentId", departmentId)
                .params("token", token)
                .params("key", "")
                .params("limit", "1000")
                .params("page", "1")
                .params("moduleName","complete")
                .params("filterByOperate", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "设备列表: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        list.clear();
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("deviceName"), jsonArray.getJSONObject(i).getString("id"));
                                list.add(bean);
                            }
                            if (list.size()==0){
                                ToastUtil.makeText(getApplicationContext(),"暂无数据");
                            }
                            adapter.refreshData(list);

                            adapter.notifyDataSetChanged();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void getDevice() {
        OkHttpUtils
                .get(NewBaseUrl.device_info_get + deviceID)
                .params("token", token)
                .params("id", deviceID)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", ": 设备类别详情" + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            list1.clear();
                            JSONObject Jpage = jsonObj.getJSONObject("device");
                            JSONObject Jpage1 = Jpage.getJSONObject("deviceTypeEntity");

                            try {
                                JSONArray jsonArray1 = Jpage1.getJSONArray("completeEquipmentInspectionProjectList");

                                for (int i = 0; i < jsonArray1.size(); i++) {
                                    ItemTypeBean bean1 = new ItemTypeBean();
                                    JSONObject sa = jsonArray1.getJSONObject(i);
                                    bean1.setId(sa.getString("id"));
                                    bean1.setName(sa.getString("dictValue"));
                                    bean1.setNo(sa.getString("dictLabel"));
                                    bean1.setContent1(sa.getString("field1"));
                                    bean1.setContent2(sa.getString("field2"));
                                    bean1.setRemark(sa.getString("remark"));
                                    bean1.setStatus(sa.getString("dataStatus"));
                                    list1.add(bean1);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (list1.size()==0){
                                ToastUtil.makeText(getApplicationContext(),"无完好检查项目，请联系管理员添加");
                            }
                            adapter1.refreshData(list1);



                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }
    public void add() {
        if (deviceID.equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择设备");
            return;
        }


        StringBuilder items=new StringBuilder();
        if (list1.size()<=0){
            ToastUtil.makeText(getApplicationContext(),"无完好检查项目，请联系管理员添加");
            return;
        }
        for (int i=0;i<list1.size();i++){
            ItemTypeBean bean=list1.get(i);
            String status=bean.getCheck_status();

            if (items.length()<=0){
                items.append(bean.getId()).append(":").append(status);
            }
            else {
                items.append(";").append(bean.getId()).append(":").append(status);

            }

            ToastUtil.print(items.toString());
        }

        Map<String, String> map = new HashMap<String, String>();
        map.put("departmentId", departmentId);
        map.put("deviceId", deviceID);
        map.put("remark", etRemark.getText().toString());
        map.put("deviceCompleteEquipmentItems", items.toString());

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.completeequipmentrecord_save)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "新增完好检查: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });

    }
    @OnClick({R.id.tv_device})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_device:
                DialogUtils.showDialog(this, NetworkEnum.DEVICE, mCompanyId,new HashMap<String, String>(){{put("departmentId",departmentId);}}, new DefaultAcitonCallback() {
                    @Override
                    public void run(ItemListBean bean1, Dialog dialog) {
                        deviceID = bean1.getID();
                        tvDevice.setText(bean1.getName());
                        getDevice();
                        dialog.dismiss();
                    }
                });
                break;

        }
    }

    @Override
    public void onDetailClick(ItemTypeBean bean) {
        message(2,bean);
    }

    @Override
    public void onCheckClick(ItemTypeBean bean) {

    }

    public void message(int type, ItemTypeBean bean) {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        View v = factory.inflate(R.layout.dialog_item_type, null);

        TextView content1= (TextView) v.findViewById(R.id.tv_content1);
        TextView content2= (TextView) v.findViewById(R.id.tv_content2);
        TextView content3= (TextView) v.findViewById(R.id.tv_content3);
        TextView content4= (TextView) v.findViewById(R.id.tv_content4);
        TextView content5= (TextView) v.findViewById(R.id.tv_content5);
        TextView content6= (TextView) v.findViewById(R.id.tv_content6);
        RelativeLayout rl3= (RelativeLayout) v.findViewById(R.id.rl3);
        RelativeLayout rl4= (RelativeLayout) v.findViewById(R.id.rl4);
        content1.setText(bean.getNo());
        content2.setText(bean.getName());

        content5.setText(bean.getRemark());
        content6.setText(bean.getStatus());
        if (type==1){
            content3.setText(bean.getContent1());
            content4.setText(bean.getContent2());
        }
        else {
            rl3.setVisibility(View.GONE);
            rl4.setVisibility(View.GONE);

        }

        builder                //对话框的标题
                .setTitle(bean.getName())
                //设定显示的View
                .setView(v)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {



                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();

    }
}
